<script setup>
import { Modal } from 'ant-design-vue'
import { CaretDownFilled, DeleteOutlined, DownOutlined, EditOutlined, PlusOutlined, ReloadOutlined, SettingOutlined, UpOutlined } from '@ant-design/icons-vue'
import { addTask, deleteTask, getExcuteList, getMode, getTaskList, getType, startOneTask, startTask, stopTask, updateTask } from '~@/api/task/index'

defineOptions({
  name: 'Task',
})
const router = useRouter()
// 新增任务
const taskForm = ref()
const taskTitle = shallowRef('')
const taskOpen = ref(false)
const rules = computed(() => {
  return {
    jobGroup: [
      { required: true, message: '必填字段', trigger: 'change' },
    ],
    jobDesc: [
      { required: true, message: '必填字段', trigger: 'change' },
    ],
    author: [
      { required: true, message: '必填字段', trigger: 'change' },
    ],
    scheduleType: [
      { required: true, message: '必填字段', trigger: 'change' },
    ],
    scheduleConf: [
      { required: true, message: '必填字段', trigger: 'change' },
    ],
    glueType: [
      { required: true, message: '必填字段', trigger: 'change' },
    ],
    executorHandler: [
      { required: true, message: '必填字段', trigger: 'change' },
    ],

  }
})
const formState = reactive({
  id: null,
  jobGroup: null,
  jobDesc: '',
  author: '',
  scheduleType: '',
  scheduleConf: '',
  glueType: '',
  executorHandler: '',
  executorParam: '',
  executorRouteStrategy: 'FIRST',
  childJobId: null,
  misfireStrategy: 'DO_NOTHING',
  executorBlockStrategy: 'SERIAL_EXECUTION',
})

// 执行一次
const oneForm = ref()
const oneOpen = ref(false)
const oneFormState = reactive({
  id: null,
  executorParam: '',
  addressList: '',
})
const locale = ref(['cn'])// 设置语言为中文，默认为中文
const statusMap = {
  0: '关闭',
  1: '运行中',
  2: '上线',
  3: '错误',
}
const message = useMessage()
const columns = shallowRef([
  {
    title: '任务ID',
    dataIndex: 'id',
    width: 150,
  },
  {
    title: '任务描述',
    dataIndex: 'jobDesc',
    width: 220,
  },
  {
    title: '调度类型',
    dataIndex: 'scheduleType',
    width: 200,
  },
  {
    title: '运行模式',
    dataIndex: 'glueType',
    width: 250,
  },
  {
    title: '负责人',
    dataIndex: 'author',
    width: 120,
    // align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'triggerStatus',
    width: 120,
    align: 'center',
  },

  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 120,

  },
])
const excuteOptions = shallowRef([])
const typeList = shallowRef([])
const modeList = shallowRef([])
const statusOptions = shallowRef([
  { configKey: -1, configValue: '全部' },
  { configKey: 0, configValue: '停止' },
  { configKey: 1, configValue: '启动' },
])
const routeOptions = shallowRef([
  { id: 'FIRST', title: '第一个' },
])

const loading = shallowRef(false)
const totalNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const formModel = reactive({
  jobGroup: void 0,
  jobDesc: void 0,
  triggerStatus: void 0,
  executorHandler: void 0,
  author: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})
onMounted(() => {
  getExcute()
  formModel.triggerStatus = statusOptions.value[0].configKey
  init()
})
// 获取执行器列表
async function getExcute() {
  try {
    const res = await getExcuteList()
    // window.location.href='https://heren-pay-reconciliation.cn-hangzhou.oss.aliyuncs.com/test/card/bill/CARD_RECHARGE20250307.xls'
    excuteOptions.value = res.data
  }
  catch (e) {
  }
  finally {
    console.log(22)
  }
}
// 处理状态
function handleStatus(text) {
  switch (text) {
    case 0:
      return 'STOP'
    default:
      return 'RUNNING'
  }
}

// 搜索
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const createBeginTime = formModel.cardDate?.[0]?.format('YYYY-MM-DD')
    const createEndTime = formModel.cardDate?.[1]?.format('YYYY-MM-DD')
    const { data } = await getTaskList({
      param: { ...formModel, createBeginTime, createEndTime },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    // dataSource.value = data.data ?? []
    totalNum.value = data.pageInfo.total
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 查询调度类型
async function getTypeList() {
  try {
    const { data } = await getType({})
    typeList.value = data ?? []
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 查询运行模式
async function getModeList() {
  try {
    const { data } = await getMode({})
    modeList.value = data ?? []
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
async function onSearch() {
  pagination.current = 1
  await init()
}
async function onReset() {
  formModel.jobGroup = void 0
  formModel.jobDesc = void 0
  formModel.triggerStatus = -1
  formModel.executorHandler = void 0
  formModel.author = void 0
  await init()
}
// 删除任务
async function handleDelete(record) {
  Modal.confirm({
    title: '确认操作',
    content: `确定要删除定时任务 “${record.jobDesc}” 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = deleteTask(record.id)
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              message.success('操作成功')
              init()
              resolve() // 关闭对话框
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}
// 启动任务
async function handleStart(record) {
  Modal.confirm({
    title: '确认操作',
    content: `确定要启动定时任务 “${record.jobDesc}” 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = startTask(record.id)
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              message.success('操作成功')
              init()
              resolve() // 关闭对话框
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}
// 停止任务
async function handleStop(record) {
  Modal.confirm({
    title: '确认操作',
    content: `确定要停止定时任务 “${record.jobDesc}” 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = stopTask(record.id)
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              message.success('操作成功')
              init()
              resolve() // 关闭对话框
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}

// 新增定时任务
function addTaskList() {
  getTypeList()
  getModeList()
  if (taskForm.value) {
    taskForm.value.resetFields()
  }
  resetTask()
  taskTitle.value = '新增定时任务'
  taskOpen.value = true
}
// 重置任务信息
function resetTask() {
  formState.author = void 0
  formState.childJobId = void 0
  formState.executorBlockStrategy = 'SERIAL_EXECUTION'
  formState.executorHandler = void 0
  formState.executorRouteStrategy = 'FIRST'
  formState.glueType = void 0
  formState.id = void 0
  formState.jobDesc = void 0
  formState.jobGroup = void 0
  formState.executorParam = void 0
  formState.misfireStrategy = 'DO_NOTHING'
  formState.scheduleConf = void 0
  formState.scheduleType = void 0
}
// 确认新增定时任务
async function handleOk() {
  try {
    await taskForm.value.validate()
    if (formState.id) {
      const { data } = await updateTask(formState)
      if (data.code === 'SUCCESS') {
        taskOpen.value = false
        message.success('保存成功')
        init()
      }
    }
    else {
      const { data } = await addTask(formState)
      if (data.code === 'SUCCESS') {
        taskOpen.value = false
        message.success('新增成功')
        init()
      }
    }
  }
  catch (error) {
    // message.error('请检查表单填写是否正确')
  }
}
// 编辑定时任务
async function handleEdit(record) {
  taskOpen.value = true
  formState.id = record.id
  formState.jobGroup = record.jobGroup
  formState.jobDesc = record.jobDesc
  formState.author = record.author
  formState.scheduleType = record.scheduleType
  formState.scheduleConf = record.scheduleConf
  formState.glueType = record.glueType
  formState.executorHandler = record.executorHandler
  formState.executorParam = record.executorParam
  formState.executorRouteStrategy = record.executorRouteStrategy
  formState.childJobId = record.childJobId
  formState.misfireStrategy = record.misfireStrategy
  formState.executorBlockStrategy = record.executorBlockStrategy
  taskTitle.value = '编辑定时任务'
}
// 打开执行一次弹窗
function handleOneStart(record) {
  resetOneForm()
  oneFormState.id = record.id
  oneOpen.value = true
}
// 查询日志
function viewDetail(record) {
  router.push({
    path: '/task/log',
    query: {
      jobGroup: record.jobGroup,
      jobId: record.id,
    },
  })
}
// 清除执行一次表单内容
async function resetOneForm() {
  oneFormState.id = void 0
  oneFormState.executorParam = void 0
  oneFormState.addressList = void 0
}
// 确定执行一次
async function handleOneOk() {
  try {
    const { data } = startOneTask(oneFormState)
    message.success('执行一次成功')

    init()
    oneOpen.value = false
  }
  catch (error) {
    // message.error('请检查表单填写是否正确')
  }
}
function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}
function handleCheckChange(value) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}
const expand = ref(false)
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :label-col="{ span: 5 }" :model="formModel">
        <a-row :gutter="[15, 0]">
          <a-col :span="8">
            <a-form-item name="jobGroup" label="执行器">
              <a-select v-model:value="formModel.jobGroup" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in excuteOptions" :key="item.id" :value="item.id">
                  {{ item.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="triggerStatus" label="状态">
              <a-select v-model:value="formModel.triggerStatus" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in statusOptions" :key="item.configKey" :value="item.configKey">
                  {{ item.configValue }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="jobDesc" label="任务描述">
              <a-input v-model:value="formModel.jobDesc" placeholder="请输入任务描述" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="executorHandler" label="运行模式">
              <a-input v-model:value="formModel.executorHandler" placeholder="模糊查询" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item name="author" label="负责人">
              <a-input v-model:value="formModel.author" placeholder="请输入负责人" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <a-space flex justify-end w-full>
              <!-- :loading="loading" -->
              <a-button type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card title="定时任务列表">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="addTaskList()">
            <template #icon>
              <PlusOutlined />
            </template>
            新增
          </a-button>
        </a-space>
      </template>
      <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'scheduleType'">
            <span>{{ record.scheduleType }} ： {{ record.scheduleConf }} </span>
          </template>
          <template v-else-if="column.dataIndex === 'glueType'">
            <span>{{ record.glueType }} ： {{ record.executorHandler }} </span>
          </template>
          <template v-else-if="column.dataIndex === 'triggerStatus'">
            <a-tag
              :color="record.triggerStatus === 0 ? 'volcano' : 'green'"
            >
              {{ handleStatus(record.triggerStatus) }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-dropdown>
              <a class="ant-dropdown-link" style="border-radius:3px;padding:5px 10px;color:#344563;background-color: rgba(9, 30, 66, .08);" @click.prevent>
                操作 <CaretDownFilled style="font-size: 11px;margin-left: 5px;" />
              </a>
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="handleOneStart(record)">
                    执行一次
                  </a-menu-item>
                  <a-menu-item @click="viewDetail(record)">
                    查询日志
                  </a-menu-item>
                  <a-divider />
                  <a-menu-item v-if="record.triggerStatus === 0" @click="handleStart(record)">
                    启动
                  </a-menu-item>
                  <a-menu-item v-else @click="handleStop(record)">
                    停止
                  </a-menu-item>
                  <a-menu-item @click="handleEdit(record)">
                    编辑
                  </a-menu-item>
                  <a-menu-item @click="handleDelete(record)">
                    删除
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增定时任务 -->
    <a-modal v-model:open="taskOpen" width="900px" :title="taskTitle" :body-style="{ paddingTop: '5px', paddingBottom: '30px' }" ok-text="保存" @ok="handleOk">
      <a-form
        ref="taskForm"
        :model="formState"
        :rules="rules"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <div class="taskTitle">
          基础配置
        </div>
        <a-row gutter="{16}">
          <a-col :span="12">
            <a-form-item name="jobGroup" label="执行器">
              <a-select v-model:value="formState.jobGroup" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in excuteOptions" :key="item.id" :value="item.id">
                  {{ item.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item name="author" label="负责人">
              <a-input v-model:value="formState.author" placeholder="请输入负责人" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="jobDesc" label="任务描述">
              <a-input v-model:value="formState.jobDesc" placeholder="请输入任务描述" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
        <div class="taskTitle">
          调度配置
        </div>
        <a-row gutter="{16}">
          <a-col :span="12">
            <a-form-item name="scheduleType" label="调度类型">
              <a-select v-model:value="formState.scheduleType" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in typeList" :key="item.configKey" :value="item.configKey">
                  {{ item.configValue }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="scheduleConf" label="Cron">
              <!-- <vue-cron v-model:value="formState.scheduleConf" /> -->
              <a-input v-model:value="formState.scheduleConf" placeholder="cron表达式..." allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
        <div class="taskTitle">
          任务配置
        </div>
        <a-row>
          <a-col :span="12">
            <a-form-item name="glueType" label="运行模式">
              <a-select v-model:value="formState.glueType" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in modeList" :key="item.configKey" :value="item.configKey">
                  {{ item.configValue }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="executorHandler" label="JobHandler">
              <a-input v-model:value="formState.executorHandler" placeholder="请输入JobHandler" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="任务参数">
              <a-textarea v-model:value="formState.executorParam" placeholder="请输入任务参数" :rows="4" />
            </a-form-item>
          </a-col>
        </a-row>
        <div class="taskTitle">
          高级配置
        </div>
        <a-row gutter="{16}">
          <a-col :span="12">
            <a-form-item label="路由策略">
              <a-select v-model:value="formState.executorRouteStrategy" placeholder="请选择" allow-clear>
                <a-select-option v-for="item in routeOptions" :key="item.id" :value="item.id">
                  {{ item.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="子任务ID">
              <a-input v-model:value="formState.childJobId" placeholder="请输入子任务ID,如存在多个则逗号分隔" allow-clear />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 执行一次 -->
    <a-modal v-model:open="oneOpen" width="600px" title="执行一次" :body-style="{ paddingTop: '30px', paddingBottom: '30px' }" ok-text="执行" @ok="handleOneOk">
      <a-form
        ref="oneForm"
        :model="oneFormState"
        :rules="rules"
        name="basic"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-form-item
          label="任务参数："
        >
          <a-input v-model:value="oneFormState.executorParam" placeholder="请输入任务参数" />
        </a-form-item>
        <a-form-item
          label="机器地址："
        >
          <a-textarea v-model:value="oneFormState.addressList" placeholder="请输入本次执行的机器地址，为空则从执行器获取" :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
  </page-container>
</template>

<style lang="less" scoped>
:deep(.ant-divider-horizontal){
    margin:5px 0;
  }
.taskTitle{
  color:gray;
  width: 100%;
  padding:5px 0;
  border-bottom:1px solid #f1eded;
  margin-bottom: 20px;
  }
.red{
      color:red;
      /* color:#ff4d4f; */
    }
.card-title{
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      flex: auto;
      color: rgba(0, 0, 0, 0.88);
      font-weight: 600;
      font-size: 16px;
      line-height: 1.5;
}
@media screen and (max-width: 1200px) and (min-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      margin-left: -44px;
      .statItem {
        padding: 0 16px;
      }
    }
  }

  @media screen and (max-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      float: none;
      margin-right: 0;
      .statItem {
        padding: 0 16px;
        text-align: left;
        &::after {
          display: none;
        }
      }
    }
  }

  @media screen and (max-width: 768px) {
    .extraContent {
      margin-left: -16px;
    }
    .projectList {
      .projectGrid {
        width: 50%;
      }
    }
  }

  @media screen and (max-width: 576px) {
    .pageHeaderContent {
      display: block;
      .content {
        margin-left: 0;
      }
    }
    .extraContent {
      .statItem {
        float: none;
      }
    }
  }

  @media screen and (max-width: 480px) {
    .projectList {
      .projectGrid {
        width: 100%;
      }
    }
  }
  </style>
